package com.xzcs.util.common;

import com.xzcs.exception.CustomException;
import freemarker.template.Template;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class GeneratorUtils {

    /**
     * 获取配置信息
     * @return
     * @throws CustomException
     */
    public static Configuration getConfig() throws CustomException {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new CustomException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取模板
     * @return
     */
    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("generator/Mapper.java.flt");
        templates.add("generator/Mapper.xml.flt");
        templates.add("generator/Service.java.flt");
        templates.add("generator/Controller.java.flt");
        templates.add("generator/frame.html.flt");
        templates.add("generator/edit.html.flt");
        return templates;
    }

    /**
     * 表名转换成Java类名
     * @param tableName
     * @return
     */
    public static String tableNameToJavaName(String tableName) {
        tableName = tableName.substring(tableName.indexOf("_") + 1);
        return WordUtils.capitalizeFully(tableName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String pkgName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(pkgName)) {
            packagePath += pkgName.replace(".", File.separator) + File.separator;
        }

        if (template.contains("Mapper.xml.flt")) {
            return packagePath + "mapper" + File.separator + className + "Mapper.xml";
        }
		if(template.contains("Mapper.java.flt")){
			return packagePath + "mapper" + File.separator + className + "Mapper.java";
		}

        if (template.contains("Service.java.flt")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains("Controller.java.flt")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains("frame.html.flt")) {
            return "main" + File.separator + "webapp" + File.separator + className + File.separator + "frame.html";
        }
        if (template.contains("edit.html.flt")) {
            return "main" + File.separator + "webapp" + File.separator + className + File.separator + "edit.html";
        }
        return null;
    }

    public static void generatorCode(HttpServletRequest request, Map<String, Object> table,
                                     List<Map<String, Object>> columns, ZipOutputStream zip) {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setServletContextForTemplateLoading(request.getServletContext(), "/WEB-INF/templates");
        String tableName = com.xzcs.util.common.StringUtils.get(table, "table_name");
        String className = tableNameToJavaName(tableName);
        List<String> templates = getTemplates();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("package", "com.xzcs");
        map.put("author", "changs");
        map.put("createDate", DateUtils.getToday("yyyy-MM-dd HH:mm:ss"));
        for (Map<String, Object> column : columns) {
            if ("PRI".equalsIgnoreCase(com.xzcs.util.common.StringUtils.get(column, "column_key"))) {
                map.put("pk", column);
            }
        }
        map.putAll(table);
        map.put("className", className);
        map.put("classname", StringUtils.uncapitalize(className));
        map.put("columns", columns);
        for (String template : templates) {
            //获取模板
            try {
                Template tpl = cfg.getTemplate(template, "UTF-8");
                StringWriter sWriter = new StringWriter();
                //将模板和数据进行组装，然后存入到StringWriter中
                tpl.process(map, sWriter);
                zip.putNextEntry(new ZipEntry(getFileName(template, className, "com.xzcs")));
                IOUtils.write(sWriter.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sWriter);
                zip.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
